<template>
	<view class="left clearfix bai" style="height:calc(100% - 20px);">
		<view class="tim-left-content left clearfix">
			<view class="tim-textarea-box left">
				<textarea maxlength="5000" v-model="content" @input="getContentCount" placeholder="请输入您的配音文案，不少于5个字，点击 「AI 帮写」可智能根据内容生成文案"></textarea>
			</view>
			
			<view class="tim-left-button left clearfix">
				
				<view class="tim-ai left clearfix" @click="optimizeContent()">
					<view class="tim-ai-content left clearfix">
						<view class="tim-ai-icon left">
							<image src="/static/images/ai-bj.png"></image>
						</view>
						<view class="tim-ai-text left">
							AI帮写
						</view>
					</view>
				</view>
				
				<view class="tim-ai left clearfix" style="width:105px;" @click="this.$refs.uploadPopup.open()">
					<view class="tim-ai-content left clearfix" style="width:103px;">
						<view class="tim-ai-icon left">
							<image src="/static/images/ai-bj.png"></image>
						</view>
						<view class="tim-ai-text left" style="width:65px;">
							传图识字
						</view>
					</view>
				</view>
				
				<view class="tim-ai left clearfix" style="width:80px;" @click="getClipboardData()">
					<view class="tim-ai-content left clearfix" style="width:78px;">
						<view class="tim-ai-icon left">
							<image src="/static/images/ai-bj.png"></image>
						</view>
						<view class="tim-ai-text left" style="width:35px;">
							粘贴
						</view>
					</view>
				</view>
				
				
				<view class="tim-fontsize right clearfix">
					{{fontNumber}}/{{fontTotalNumber}}
				</view>
				
				
			</view>
		</view>
		
		
		<uni-popup ref="uploadPopup" type="center" border-radius="10px 10px 0 0">
			<view class="list-add-box left clearfix">
				<view class="list-add-title left relative">
					上传图片
					<view class="list-add-close absolute" @click="this.$refs.uploadPopup.close()">
						<uni-icons type="closeempty" size="20" color="#999"></uni-icons>
					</view>
				</view>
				
				<view class="list-add-textarea left clearfix">
					<uni-file-picker :sizeType="['compressed']" @success="uploadImageSuccess" :imageStyles="{width:'120px',height:'120px'}" limit="20" title=" "></uni-file-picker>
				</view>
				<view class="list-add-message left" v-if="errMssage">
					<uni-icons type="icon-cuo1" size="14" color="red" custom-prefix="iconfont" style="margin-right:3px;"></uni-icons>{{errMssage}}
				</view>
				
				<view class="list-add-message left" v-else>
					
				</view>
				
				<view class="list-add-buttons left" @click="getTextfromImage()">
					识别文字
				</view>
			</view>
		</uni-popup>
		
		
	</view>
</template>

<style scoped>
	.list-add-buttons{height:40px;background-image: linear-gradient(90deg, #4287fe, #298bfe 25%, #0f8ffd 51%, #25b4c1);text-align: center;line-height:40px;color:#fff;border-radius: 20px;font-size:15px;cursor: pointer;width:30%;margin-left:35%;margin-top:20px;}
	.list-add-textarea input{width:100%;height:50px;border-radius: 5px;border:1px solid #eee;margin-top:50px;padding-left:10px;font-size:15px;}
	.list-add-textarea{width: calc(80% - 10px);margin-left:10%;margin-top:20px;height:320px;overflow: auto;}
	.list-add-close{right:10px;top:2px;cursor: pointer;}
	.list-add-title{width:calc(100% - 20px);padding-left:20px;line-height:50px;text-align: left;font-size:15px;font-weight:500;color:#444;}
	.list-add-box{width:900px;height:500px;background:#fff;border-radius: 10px;}
	.tim-fontsize{width:100px;line-height:40px;height:40px;margin-right:20px;font-size:14px;color:#999;text-align:center;}
	.tim-ai-text{width:50px;height:34px;line-height:34px;font-size:14px;color:#2468f2;font-weight:500;}
	.tim-ai-icon image{width:100%;height:100%;}
	.tim-ai-icon{width:20px;height:20px;margin:7px;}
	.tim-ai-content{width:88px;height:34px;margin:1px;background:#fff;border-radius: 8px;}
	.tim-ai{cursor:pointer;margin-left:20px;width:90px;height:36px;background:#fff;border-radius: 8px;background-image:linear-gradient(90deg, rgba(44, 212, 151, .5), rgba(86, 204, 218, .5) 10%, rgba(94, 181, 255, .5) 25%, rgba(36, 104, 242, .5) 40% 60%, rgba(187, 84, 110, .5) 87%, rgba(235, 94, 62, .5));}
	.tim-left-button{width:100%;height:40px;margin-top:5px;}
	.tim-left-content:hover{border:1px solid #2979ff;}
	.tim-textarea-box textarea{width:100%;height:100%;min-height:100px;font-size:15px;color:#444;line-height:30px;}
	.tim-textarea-box{width:calc(100% - 40px);padding:20px;min-height:100px;height:calc(100% - 100px);}
	.tim-left-content{width:calc(100% - 40px);margin-left:20px;height:calc(100% - 70px);background-color: rgb(247, 247, 249);margin-top:20px;border-radius: 5px;background-image: url('/static/images/body-bj.png');background-size: 100%;border:1px solid #efefef;}
</style>

<script>
	var db = uniCloud.database();
	var chat = uniCloud.importObject('chat',{customUI:true});
	var aliyun = uniCloud.importObject('aliyun',{customUI:true});
	var global = uniCloud.importObject('global',{customUI:true});
	var apiKey = 'sk-4a0cd1cdc85147c785ea8a8ddd1dcd38';
	export default {
		name:"create-textarea",
		data() {
			return {
				content:'',
				image:[],
				fontNumber:0
			};
		},
		props:['chapter','defaultContent','fontTotalNumber'],
		watch:{
			"content"(val){
				this.$emit('change',val);
			},
			"defaultContent"(val){
				this.content = val;
				this.fontNumber = val.length;
			}
		},
		methods:{
			//粘贴内容
			getClipboardData(){
				var that = this;
				uni.getClipboardData({
					success: function (res) {
						const data = res.data;
						that.content = data.replace(/<[^>]*>?/g, '').replace(/#/g, '');
						that.fontNumber = that.content.length;
					}
				});
			},
			//从图片中识别出文本出来
			async getTextfromImage(){
				var image = this.image;
				if(image.length < 1){
					uni.showToast({
						title:'请至少上传一张带文本的图片',
						icon:'none',
						duration:3000
					})
					
					return false;
				}
				uni.showLoading({
					title:'识别中···'
				})
				var content = this.image;
				this.streamChatCompletion(content);
				  
			},
			
			//上传图片成功以后
			uploadImageSuccess(e){
				console.log('上传图片成功以后',e);
				var tempFilePaths = e.tempFilePaths;
				var tempFiles = e.tempFiles;
				for(var i = 0;i<tempFilePaths.length;i++){
					var size = tempFiles[i].size;
					if(size > 1000000){
						uni.showToast({
							title:'上传图片不能大于10MB，建议传图时不要选择传原图',
							icon:'none',
							duration:4000
						})
						
						return false;
					}
					this.image.push({type:'image_url',image_url:{url:tempFilePaths[i]}});
				}
				this.image.push({type:'text',text:'识别图中文本和标题，保留段落换行，不要识别页码'});
			},
			//统计内容中的字数
			getContentCount(){
				this.fontNumber = this.content.length;
				this.audioScore = Math.ceil(this.fontNumber * 0.003);
				this.videoScore = Math.ceil(this.fontNumber * 0.006);
			},
			//一键优化内容
			optimizeContent(){
				var content = this.content;
				if(this.chapter && this.chapter.title){
					var title = this.chapter.title;
				}else{
					var title = '';
				}
				
				if(!content && !title){
					uni.showToast({
						title:'请输入标题和内容',
						icon:'none',
						duration:3000
					})
					
					return false;
				}
				uni.showLoading({
					title:'优化中···'
				})
				var text = content?content:title;
				var param = [
					{
						type:'text',
						text:text+'帮我扩写下以上内容，字数不要超过1600字，直入正题，不要其他多余说明。'
					}
				]
				
				this.streamChatCompletion(param,'qwen-max');
			},
			//流式调用数据
			async streamChatCompletion(content,model='qwen-vl-max') {
				var that = this;
				that.content = '';
				that.optimize = true;
			    const url = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
			    const requestOptions = {
			        method: 'POST',
			        headers: {
			            'Authorization': 'Bearer '+apiKey,
			            'Content-Type': 'application/json',
			            'X-DashScope-Async': 'enable'
			        },
			        body: JSON.stringify({
			            model: model,
			            stream: true,
			            messages: [
			                {
			                    role: 'user',
			                    content: content
			                }
			            ]
			        })
			    };
			
				
			    try {
			        const response = await fetch(url, requestOptions);
			        if (!response.ok) {
			            throw new Error(`请求错误: ${response.status}`);
			        }
			
			        const reader = response.body.getReader();
			        const decoder = new TextDecoder('utf-8');
			        let result = '';
			        while (true) {
			            const { done, value } = await reader.read();
			            if (done) {
							that.optimize = false;
			                break;
			            }
			            const chunk = decoder.decode(value);
			            const lines = chunk.split('\n');
			            for (const line of lines) {
			                if (line.startsWith('data: ')) {
			                    const data = line.slice(6);
			                    if (data === '[DONE]') {
									that.optimize = false;
			                        break;
			                    }
			                    try {
			                        const jsonData = JSON.parse(data);
			                        const content = jsonData.choices[0].delta.content;
			                        if (content) {
										uni.hideLoading()
										that.$refs.uploadPopup.close();
			                            that.content += content.replace(/[*#---]/g, '').replace(/(?<!\n)\n(?!\n)/g, '');
										that.fontNumber = that.content.length;
										that.getContentCount();
										
										
			                        }
			                    } catch (error) {
									that.optimize = false;
									that.$refs.uploadPopup.close();
									uni.hideLoading()
			                    }
			                }
			            }
			        }
			    } catch (error) {
					that.$refs.uploadPopup.close();
					uni.hideLoading()
			    }
			},
		}
	}
</script>
